//
//  NewfeatureCollectionViewController.swift
//  SwiftWeiBo
//
//  Created by wyw on 16/10/18.
//  Copyright © 2016年 Style_Y. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class NewfeatureCollectionViewController: UICollectionViewController {
    
    private let pageCount = 4
    private var layout : UICollectionViewFlowLayout = NewfeatureLayout()
    
    init() {
       super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.register(NewfeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return 4
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! NewfeatureCell
    
        // Configure the cell
        cell.imageIndex = indexPath.item
    
        return cell
    }

    // MARK: UICollectionViewDelegate
    override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        let path = collectionView.indexPathsForVisibleItems.last
        
        if path!.item == (pageCount - 1) {
            
            let cell = collectionView.cellForItem(at: path!) as! NewfeatureCell
            
            // 执行动画
            cell.startAnimation()
           
        }
    }

}

// 自定义cell
private class NewfeatureCell: UICollectionViewCell {
    
    fileprivate var imageIndex : Int? {
       
        didSet {
            imageView.image = UIImage(named: "new_feature_\(imageIndex! + 1)")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    fileprivate func startAnimation() {
        startBtn.isHidden = false
        
        // 执行动画
        startBtn.transform = CGAffineTransform.init(scaleX: 0.0, y: 0.0)
        startBtn.isUserInteractionEnabled = false
        
        UIView.animate(withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 2, initialSpringVelocity: 5, options: UIViewAnimationOptions.allowAnimatedContent, animations: {
            self.startBtn.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.0)
            }, completion: { (_) in
                self.startBtn.isUserInteractionEnabled = true
        })
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView .addSubview(imageView)
        contentView.addSubview(startBtn)
        imageView.frame = contentView.bounds
        
        let SCREENHEIGHT = UIScreen.main.bounds.size.height
        let SCREENWIDTH = UIScreen.main.bounds.size.width
        
        startBtn.frame = CGRect(x: (SCREENWIDTH - 186)*0.5, y: SCREENHEIGHT - 160, width: 186, height: 50)
    }
    
    func customBtnClick() {
//        print("----------------")
        // 切换到主页
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: SwitchRootViewControllerKey), object: true)
    }
    
    // MARK: - 懒加载
    private lazy var imageView = UIImageView()
    fileprivate lazy var startBtn : UIButton = {
        let btn = UIButton()
        
        btn.setImage(UIImage(named: "new_feature_button"), for: UIControlState.normal)
        btn.setImage(UIImage(named:"new_feature_button_highlighted"), for: UIControlState.highlighted)
        
        btn.isHidden = true
        
        btn.addTarget(self, action: #selector(NewfeatureCell.customBtnClick), for: UIControlEvents.touchUpInside)
        
        return btn
    }()
    
}

private class NewfeatureLayout : UICollectionViewFlowLayout {

    private override func prepare() {
        // 1.设置布局属性
        itemSize = UIScreen.main.bounds.size
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.horizontal
        
        // 2.设置collectionView属性
        collectionView?.bounces = false
        //        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.isPagingEnabled = true
    }
    
}



